package cn.ztydata.teachingsystem.heaven.service;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.common.WebContext;
import cn.ztydata.teachingsystem.heaven.cons.GroupType;
import cn.ztydata.teachingsystem.heaven.cons.Roles;
import cn.ztydata.teachingsystem.heaven.dao.CommentDao;
import cn.ztydata.teachingsystem.heaven.dao.SpeakDao;
import cn.ztydata.teachingsystem.heaven.dao.redis.SpeakComCountDao;
import cn.ztydata.teachingsystem.heaven.entity.Comment;
import cn.ztydata.teachingsystem.heaven.entity.Student;
import cn.ztydata.teachingsystem.heaven.entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 发言回复业务类
 *
 * @author lyj
 * @since 2015-3-20
 */
@Service
public class CommentService extends BaseService {
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private WebContext webContext;
    @Autowired
    private SpeakDao speakDao;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private SpeakComCountDao speakComCountDao;


    //<editor-fold desc="验证">
    /**
     * 验证角色
     * @param groupType 群组类型
     * @return void
     * @author lyj
     * @since 2015-5-7
     */
    public void checkRole(final int groupType) {
        //角色验证
        Boolean checkRole = true;
        if (groupType == GroupType.COURSE_GROUP || groupType == GroupType.CLASS_GROUP) {
            if (webContext.getRole() != Roles.TEACHER && webContext.getRole() != Roles.STUDENT) {
                checkRole = false;
            }
        } else if (groupType == GroupType.SPEC_GROUP) {
            if (webContext.getRole() != Roles.SPEC_LEADER && webContext.getRole() != Roles.TEACHER) {
                checkRole = false;
            }
        }

        if (!checkRole){
            log.warn("当前登录用户没有权限使用该功能！");
            throw new ServiceException("权限错误！");
        }
    }


    /**
     * 验证权限
     *
     * @param speakId 发言ID
     * @param id 回复ID
     * @param groupType 群组类型
     * @return boolean
     * @param teacherNum 登录用户工号或学号
     * @author lyj
     * @since 2015-3-26
     */
    public void checkRole(final long speakId, final long id, final int groupType, final String teacherNum) {

        Boolean check = false;

        //判断是否为回复的创建人，判断回复是否还存在
        if (commentDao.getById(id) == 1) {
            check = true;
        }

        if (webContext.getRole() != Roles.STUDENT) {

            //判断发言所在群组是否为老师所管理的群组
            if (groupType == GroupType.COURSE_GROUP) { //验证课程群组
                if (speakDao.checkGroup(speakId) == 1) {
                    check = true;
                }
            } else if (groupType == GroupType.CLASS_GROUP) { //验证班级群组
                if (speakDao.checkClassGroup(speakId, teacherNum, groupType) == 1) {
                    check = true;
                }
            } else if (groupType == GroupType.SPEC_GROUP) { //验证专业群组
                if (speakDao.checkSpecGroup(speakId, groupType) == 1) {
                    check = true;
                }
            }
        }

        if (!check) {
            log.warn("权限错误！");
            throw new ServiceException("回复已经被删除或权限错误！");
        }
    }

    //</editor-fold>

    //<editor-fold desc="新增">
    /**
     * 新增回复
     *
     * @param comment 回复实体
     * @return void
     * @author lyj
     * @since 2015-3-23
     */
    public void addComment(Comment comment) {

        //角色验证
        checkRole(comment.getGroupType());

        //判断发言是否还存在
        if (speakDao.getById(comment.getSpeakId()) == null) {
            log.debug("speakDao.getById(comment.getSpeakId()) == null,发言已经被删除，不能再回复！");
            log.warn("新增回复时发言已经删除发言ID->{}", comment.getSpeakId());
            throw new ServiceException("发言已经被删除，不能再回复！");
        }

        if (commentDao.addComment(comment) != 1) {
            log.debug("新增回复commentDao.addComment(comment) != 1");
            log.warn("新增回复失败!");
            throw new ServiceException("新增失败");
        }

        //递增回复量
        speakComCountDao.increment(comment.getSpeakId(), speakComCountDao.COMMENT_COUNT);


    }
    //</editor-fold>

    //<editor-fold desc="删除">
    /**
     * 删除回复
     *
     * @param id 回复ID
     * @return void
     * @author lyj
     * @since 2015-3-23
     */
    public void deleteComment(final long id, final long speakId, final int groupType, final String teacherNum){
        //角色验证
        checkRole(groupType);

        checkRole(speakId, id, groupType, teacherNum);

        if (commentDao.deleteComment(id) != 1){
            log.debug("删除回复commentDao.deleteComment(id) != 1");
            log.warn("删除回复失败！");

            throw new ServiceException("删除失败！");
        }

        //递减回复量
        speakComCountDao.subIncrement(speakId, speakComCountDao.COMMENT_COUNT);
    }
    //</editor-fold>

    //<editor-fold desc="查询">
    /**
     * 获取回复列表
     *
     * @param speakId 发言ID
     * @param pageNum 当前页码
     * @param pageSize 每页条数

     * @return page
     * @author lyj
     * @since 2015-3-23
     */
    public Page<Comment> getList(final long speakId, final int pageNum, final int pageSize, final int groupType){

        //角色验证
        checkRole(groupType);

        Page<Comment> page = commentDao.getList(speakId, pageNum, pageSize);

        //存储老师ID
        Set<Long> teacherIds = new HashSet<>();
        //存储学生ID
        Set<Long> studentIds = new HashSet<>();

        if (page.getItems().size() == 0){
            log.debug("page.getItems().size() == 0");
            return page;
        }

        //循环读取创建人ID
        log.debug("循环读取创建人ID");
        for (Comment comment : page.getItems()){
            if (comment.getRole() == 0){
                log.debug("comment.getRole() == 0");
                teacherIds.add(comment.getCreatorId());
            } else {
                log.debug("comment.getRole() != 0");
                studentIds.add(comment.getCreatorId());
            }
        }

        //获取教师头像、姓名
        Map<Long, Teacher> reTeacher = teacherService.getPictures(teacherIds);
        //获取学生头像、姓名
        Map<Long, Student> reStudent = studentService.getPictures(studentIds);

        //循环绑定头像和姓名
        log.debug("循环绑定头像和姓名");
        for (Comment comment : page.getItems()){
            if (comment.getRole() == 0) {
                log.debug("1comment.getRole() == 0");
                comment.setCreatorName(reTeacher.get(comment.getCreatorId()).getName());
                comment.setCreatorPhoto(reTeacher.get(comment.getCreatorId()).getPicture());
            } else {
                log.debug("1comment.getRole() != 0");
                comment.setCreatorName(reStudent.get(comment.getCreatorId()).getName());
                comment.setCreatorPhoto(reStudent.get(comment.getCreatorId()).getAvatar());
            }
        }

        log.debug("获取回复列表");
        return page;
    }
    //</editor-fold>
}
